package cn.smartadmin.bootstrap.configuration;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class MybatisPlusConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public MetaObjectHandler commonFieldHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                Long currentUserId = 0L;//Optional.of(securityService.getUserId()).orElse(0L);
                this.strictInsertFill(metaObject, "createId", () -> currentUserId , Long.class);
                this.strictInsertFill(metaObject, "updateId", () -> currentUserId, Long.class);
                this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class);
                this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
                this.strictInsertFill(metaObject, "version", () -> Integer.valueOf(1), Integer.class);
                this.strictInsertFill(metaObject, "deleted", () -> Boolean.valueOf(false), Boolean.class);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                Long currentUserId = 0L;//Optional.of(securityService.getUserId()).orElse(0L);
                this.strictUpdateFill(metaObject, "updateId", () -> currentUserId, Long.class);
                this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
            }
        };
    }
}